package com.example.memento.download.util;

import java.net.InetAddress;
import java.util.regex.Pattern;

/**
 * IP 地址工具类
 */
public class IpUtils {
    
    private static final Pattern IPV4_PATTERN = Pattern.compile(
        "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$"
    );
    
    /**
     * 判断是否为内网 IP
     */
    public static boolean isInternalIP(String ip) {
        if (ip == null || ip.isEmpty()) {
            return false;
        }
        
        try {
            InetAddress address = InetAddress.getByName(ip);
            return address.isLoopbackAddress() 
                || address.isLinkLocalAddress() 
                || address.isSiteLocalAddress()
                || isPrivateIP(ip);
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 判断是否为私有 IP（RFC 1918）
     */
    private static boolean isPrivateIP(String ip) {
        if (!isValidIP(ip)) {
            return false;
        }
        
        // 10.0.0.0/8
        if (ip.startsWith("10.")) {
            return true;
        }
        // 172.16.0.0/12
        if (ip.startsWith("172.")) {
            String[] parts = ip.split("\\.");
            if (parts.length >= 2) {
                int second = Integer.parseInt(parts[1]);
                if (second >= 16 && second <= 31) {
                    return true;
                }
            }
        }
        // 192.168.0.0/16
        if (ip.startsWith("192.168.")) {
            return true;
        }
        // 127.0.0.0/8
        if (ip.startsWith("127.")) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 验证 IP 地址格式
     */
    public static boolean isValidIP(String ip) {
        return ip != null && IPV4_PATTERN.matcher(ip).matches();
    }
}

